import {defineStore} from 'pinia'
import {ref, computed} from "vue";
import {
    addCartApi,
    getCartListApi,
    deleteCartApi,
    selectCartApi,
    selectAllCartApi,
    updateCartApi
} from '@/api/cars/index'
import {userInfoStore} from "@/stores/useInfo";
import {ElMessage} from "element-plus";

//本地
export const carsInfoStore = defineStore('carsInfo', () => {
        let carsList = ref([])
        let userInfo = userInfoStore()
        let debounceTimer: number;

        async function getCartList() {
            if (userInfo.userInfo.token) {
                let res = await getCartListApi()
                if (res.msg == '操作成功') {
                    carsList.value = res.result
                }
            } else {
                carsList.value = []
            }
        }

        //添加
        async function getCarInfo(obj: object) {
            if (userInfo.userInfo.token) {
                let objParams = {
                    count: obj.count,
                    skuId: obj.skuId,
                }
                const res = await addCartApi(objParams)
                if (res.msg == '操作成功') {
                    ElMessage.success('添加成功')
                    getCartList()
                }
            } else {
                const item = carsList.value.find((item) => {
                    return item.skuId === obj.skuId
                })
                if (item) {
                    item.count += obj.count
                } else {
                    carsList.value.unshift(obj)
                }
            }
        }

        //单独删除
        async function removeCarInfo(skuId: string) {
            if (userInfo.userInfo.token) {
                let objParams = {
                    ids: [skuId]
                }
                const res = await deleteCartApi(objParams)
                if (res.msg == '操作成功') {
                    ElMessage.success('删除成功')
                    getCartList()
                }
            } else {
                for (let i = 0; i < carsList.value.length; i++) {
                    if (carsList.value[i].skuId === skuId) {
                        carsList.value.splice(i, 1);
                    }
                }
            }
        }


        //删除已选择
        async function removeSelectCarInfo(skuId: Array<string>) {
            if (userInfo.userInfo.token) {
                let objParams = {
                    ids: skuId
                }
                let res = await deleteCartApi(objParams)
                if (res.msg == '操作成功') {
                    ElMessage.success('删除成功')
                    getCartList()
                }
            }
        }

        //修改
        async function updateCarInfo(obj: object, index: number) {
            if (obj.id) {
                if (userInfo.userInfo.token) {
                    carsList.value[index].count = obj.count
                    //删除原有的
                    let delObjParams = {
                        ids: [carsList.value[index].skuId]
                    }
                    let res = await deleteCartApi(delObjParams)
                    if (res.msg == '操作成功') {
                        //添加新的
                        let addObjParams = {
                            skuId: obj.id,
                            count: 1
                        }
                        //获取当前的
                        let res = await addCartApi(addObjParams)
                        if (res.msg == '操作成功') {
                            getCartList()
                        }
                    }

                } else {
                    let res = obj.specs.map(item => {
                        return `${item.name}:${item.valueName}`
                    })
                    carsList.value[index].price = obj.price
                    carsList.value[index].skuId = obj.id
                    carsList.value[index].attrsText = res.join(';')
                    carsList.value[index].count = 1
                    localStorage.setItem('carsInfo', JSON.stringify(carsList.value))
                }
            }
        }

        //修改数量
        async function updateCarCount(skuId: string, count: number) {
            if (userInfo.userInfo.token) {
                let objParams = {
                    count: count
                }
                // 检查是否已经有 debounceTimer，如果没有则设置它
                let res = await updateCartApi(skuId, objParams);
                if (res.msg === '操作成功') {
                    getCartList();
                }
            }
        }

        //单选
        async function selectCarInfo(selected: boolean, skuId: string) {
            if (userInfo.userInfo.token) {
                let objParams = {
                    selected: selected,
                }
                let res = await selectCartApi(skuId, objParams)
                if (res.msg == '操作成功') {
                    getCartList()
                }
            } else {
                //查询当前skuId 返回符合的对象
                let item = carsList.value.find((item) => {
                    return item.skuId === skuId
                })
                item.selected = selected
            }


        }

        //点击全选按钮全部选中
        async function selectAllCarInfo(selected: boolean) {
            if (userInfo.userInfo.token) {
                let objSelectedArr = carsList.value.map((item) => {
                    return item.skuId
                })
                let objParams = {
                    selected: selected,
                    ids: objSelectedArr
                }
                let res = await selectAllCartApi(objParams)
                if (res.msg == '操作成功') {
                    getCartList()
                }
            } else {
                carsList.value.forEach((item) => {
                    item.selected = selected
                })
            }
        }

        //多选(判断里面的每一项是否为选中状态)
        let isAll = computed(() => {
            return carsList.value.every((item) => {
                return item.selected
            })
        })

        //计算总价（选中的）
        let totalPrice = computed(() => {
            return carsList.value.filter((item) => {
                return item.selected
            }).reduce((pre, cur) => {
                return pre + cur.price * cur.count
            }, 0)
        })

        //选中的数量
        let selectedCount = computed(() => {
            return carsList.value.filter((item) => {
                return item.selected
            }).reduce((pre, cur) => {
                return pre + cur.count
            }, 0)
        })


        return {
            carsList,
            getCarInfo,
            removeCarInfo,
            updateCarInfo,
            selectCarInfo,
            selectAllCarInfo,
            isAll,
            totalPrice,
            selectedCount,
            getCartList,
            removeSelectCarInfo,
            updateCarCount
        }
    }

    ,
    {
        persist: true,
    }
)